package com.glsc.ngateway.platform.service.it.networkAssets;

import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.it.networkassets.HostInformationMaintenance;
import com.glsc.ngateway.common.api.platform.dto.it.networkassets.HostInformationMaintenanceDto;
import com.glsc.ngateway.common.api.common.dto.PageQueryParamDto;
import com.glsc.ngateway.common.api.platform.dto.it.networkassets.NetworkAssetMaintenanceDto;
import com.glsc.ngateway.common.base.converter.platform.HostInformationMaintenanceConverter;
import com.glsc.ngateway.common.base.converter.platform.NetworkAssetMaintenanceConverter;
import com.glsc.ngateway.common.base.exception.PlatformException;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.it.networkAssets.HostInformationMaintenanceRepo;
import com.glsc.ngateway.common.api.common.utils.encrypt.AESEncrypt;
import com.glsc.ngateway.platform.utils.report.ReportFileConfigEnum;
import com.glsc.ngateway.platform.utils.report.ReportFileUtil;
import com.glsc.ngateway.platform.utils.report.ReportUploadContext;
import io.jsonwebtoken.lang.Collections;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * 网络资产-主机信息维护
 *
 * @author xuchang
 */
@Service
public class HostInformationMaintenanceService {
    private static final Logger LOGGER = LoggerFactory.getLogger(HostInformationMaintenanceService.class);
    private static final Integer USERNAME_MAX_LENGTH = 16;

    @Autowired
    private HostInformationMaintenanceRepo hostInfoMtRepo;

    @Autowired
    private NetworkAssetMaintenanceService networkAssetMaintenanceService;

    /**
     * 查看
     */
    public PageImpl<HostInformationMaintenanceDto> query(PageQueryParamDto<HostInformationMaintenanceDto> param) throws Exception {
        param.setParam(Objects.isNull(param.getParam()) ? new HostInformationMaintenanceDto() : param.getParam());
        HostInformationMaintenanceDto hostInfoMtDto = param.getParam();
        if (Objects.nonNull(hostInfoMtDto.getSnmpRoCommunity())) {
            hostInfoMtDto.setSnmpRoCommunity(AESEncrypt.encrypt(hostInfoMtDto.getSnmpRoCommunity()));
        }
        if (Objects.nonNull(hostInfoMtDto.getUsername())) {
            hostInfoMtDto.setUsername(AESEncrypt.encrypt(hostInfoMtDto.getUsername()));
        }
        Pageable pageable = param.getPageable();
        Page<HostInformationMaintenance> pageRes = hostInfoMtRepo.page(pageable, param.getParam());
        //转dto
        List<HostInformationMaintenanceDto> datas = HostInformationMaintenanceConverter.do2Dto(pageRes.getContent());
        //填充绑定资产详情
        datas.forEach(d -> {
            if(!Collections.isEmpty(d.getBindSerialNumList())) {
                List<NetworkAssetMaintenanceDto> networkMtList = NetworkAssetMaintenanceConverter.do2Dto(networkAssetMaintenanceService.findAllByBindSerialNumList(d.getBindSerialNumList()));
                d.setBindSerialDetailList(networkMtList);
            }
        });
        return new PageImpl<>(datas, pageable, pageRes.getTotalElements());
    }

    /**
     * 导出
     */
    public byte[] export(HostInformationMaintenanceDto param) throws IOException {
        List<HostInformationMaintenanceDto> datas = HostInformationMaintenanceConverter.do2Dto(hostInfoMtRepo.queryAll(param));
        return ReportFileUtil.export(datas, ReportFileConfigEnum.HOST_INFORMATION_MAINTENANCE);
    }

    /**
     * 上传文件批量编辑
     */
    public ReportUploadContext<HostInformationMaintenanceDto, String> upload(MultipartFile file) throws IOException {
        ReportUploadContext<HostInformationMaintenanceDto, String> context = ReportUploadContext.<HostInformationMaintenanceDto, String>builder()
                .config(ReportFileConfigEnum.HOST_INFORMATION_MAINTENANCE)
                .file(file)
                .check(this::check)
                .build();
        ReportFileUtil.readSingleExcel(context);
        //全部检查通过后添加或修改数据
        if (context.isCheckPass()) {
            hostInfoMtRepo.saveAll(HostInformationMaintenanceConverter.dto2Do(context.getReadRes()));
        }
        return context;
    }

    /**
     * 删除
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(@NotNull Long id) {
        hostInfoMtRepo.deleteById(id);
    }

    /**
     * 添加/修改
     */
    @Transactional(rollbackFor = Exception.class)
    public void addOrUpdate(@NotNull HostInformationMaintenanceDto hostInfoMtDto) {
        check(hostInfoMtDto);
        hostInfoMtRepo.save(HostInformationMaintenanceConverter.dto2Do(hostInfoMtDto));
    }

    /**
     * 检查数据
     */
    public void check(HostInformationMaintenanceDto hostInfoMtDto) {
        if (StringUtils.isBlank(hostInfoMtDto.getHost())) {
            throw PlatformException.error("[主机]项必填", false, false);
        }
        if (hostInfoMtRepo.countByHost(hostInfoMtDto.getId(), hostInfoMtDto.getHost()) > 0) {
            throw PlatformException.error(String.format("[host]项%s重复", hostInfoMtDto.getHost()), false, false);
        }
        if (StringUtils.isNotBlank(hostInfoMtDto.getUsername()) && hostInfoMtDto.getUsername().length() >= USERNAME_MAX_LENGTH) {
            throw PlatformException.error(String.format("用户名:%s超过最大长度:%s", hostInfoMtDto.getUsername(), USERNAME_MAX_LENGTH), false, false);
        }
        if (Collections.isEmpty(hostInfoMtDto.getBindSerialNumList())) {
            throw PlatformException.error("[绑定设备资产]项必填", false, false);
        }
        if (Collections.isEmpty(hostInfoMtDto.getDeployedModeList())) {
            throw PlatformException.error("[部署模式]项必填", false, false);
        }
    }
}
